package com.Jano.timer;

import com.Jano.dao.Impl.ProductDaoImpl;
import com.Jano.dao.ProductDao;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;

import java.util.Calendar;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.Jano.constant.BusinessConstant.*;

/**
 * description: updateTimer <br>
 * date: 2022/6/10 9:41 PM <br>
 * author: zoumaoji <br>
 * version: 1.0 <br>
 */
public class UpdateTimer {
    public void productUpdateTimer() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                /**凌晨12点更新到数据库*/
                try (JedisPool jedisPool = new JedisPool(REDIS_HOST, REDIS_POST);
                     Jedis jedis = jedisPool.getResource()) {
                    ProductDao productDao = new ProductDaoImpl();
                    Set<Tuple> category = jedis.zrangeWithScores( REDIS_PRODUCT_KEY, 0, -1);
                    for (Tuple tuple : category) {
                        productDao.updateClickCount(Integer.parseInt(tuple.getElement()), (int) tuple.getScore());
                    }
                }
            }
        };
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(runnable, INITIAL_DELAY_HOUR, PERIOD_HOUR,TimeUnit.HOURS);
    }
}
